package sample.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    private static final CookieStore httpCookieStore = new BasicCookieStore();
    private static final CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCookieStore(httpCookieStore).build();

    public static String get(String url) {
        // 响应模型
        String result =null;
        // 由客户端执行(发送)Get请求
        HttpGet httpGet = new HttpGet(url);
        result = execute(httpGet);
        return result;
    }

    public static String post(String url, Map<String, Object> paramsMap){
        HttpPost hp = new HttpPost(url);
        List<NameValuePair> params = buildParams(paramsMap);
        hp.setEntity(new UrlEncodedFormEntity(params, HTTP.DEF_CONTENT_CHARSET));
        String result = execute(hp);
        return result;
    }

    @NotNull
    private static List<NameValuePair> buildParams(Map<String, Object> paramsMap) {
        List<NameValuePair> params = new ArrayList<>();
        for (Map.Entry<String, Object> map : paramsMap.entrySet()){
            params.add(new BasicNameValuePair(map.getKey(),  (String) map.getValue()));
        }
        return params;
    }

    /**
     * 执行http请求
     * @param httpUriRequest
     * @return
     */
    private static String execute(HttpUriRequest httpUriRequest){
        CloseableHttpResponse response = null;
        String result = null;
        String url = null;
        try {
            url = httpUriRequest.getURI().toURL().toString();
            response = httpClient.execute(httpUriRequest);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            LOGGER.debug("url: {}, 响应状态为: {}, 响应内容长度为：{} ", url, response.getStatusLine(), responseEntity.getContentLength());
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
                LOGGER.debug("内容为：{}", result);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("url: {}, 错误：{}", url, e.getMessage());
        }
        return result;
    }

    public static CookieStore getCookieStore(){
        return httpCookieStore;
    }
}
